#pragma once
#include <sys/epoll.h>
#include "Log.hpp"
#include "Err.hpp"

const static int default_events_num = 1024;
const static int default_epfd = -1;
class epoll
{
public:
    epoll()
        :_events(new epoll_event[default_events_num]),_epfd(default_epfd)
    {}
    ~epoll()
    {
        delete[] _events;
    }

    void create()
    {
        _epfd = epoll_create(128);
        if(_epfd == default_epfd)
        {
            LOG(FATAL,"epoll_create error!");
            exit(EPOLL_CREATE_ERR);
        }
    }

    void add_event(int sockfd,uint32_t events)
    {
        epoll_event ev;
        ev.data.fd = sockfd;
        ev.events = events;
        int n = epoll_ctl(_epfd,EPOLL_CTL_ADD,sockfd,&ev);
        if(n == -1)
        {
            LOG(ERROR,"fd num:%d -> epoll_ctl error!",sockfd);
        }
    }

    int wait(int timeout)
    {
       int n = epoll_wait(_epfd,_events,default_events_num,timeout);
       return n;// 逻辑判断交给调用方
    }

    int get_events_fd(int pos)
    {
        return _events[pos].data.fd;
    }
    
    uint32_t get_events(int pos)
    {
        return _events[pos].events; 
    }
protected:
    epoll_event *_events;
    int _epfd;
};